import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 攻击组件
 * 
 * 按照技能的特性来提供计算伤害的时机与结束状态重置的时机，不提供具体的伤害计算的方法
 */
@ccclass('AttackAction')
export class AttackAction extends Component {

    private isAttack: boolean;
    // 计算伤害时间(有前摇)
    private hurtTime: number;
    // 计算伤害
    private onHurtFunc: Function;

    private endTime: number;
    // 结束状态重置
    private onEndFunc: Function;

    private nowTime: number = 0;

    public init(): void {
        this.isAttack = false;
        this.hurtTime = 0;
        this.onHurtFunc = null;
        this.endTime = 0;
        this.onEndFunc = null;
    }

    /**
     * 判断是否可以攻击,并设置回调时间
     * @param hurtTime 
     * @param hurtFunc 
     * @param endTime 
     * @param endFunc 
     * @returns 
     */
    public canAttack(hurtTime?: number, hurtFunc?: Function, endTime?: number, endFunc?: Function) {
        if (this.isAttack) {
            return false;
        }
        this.hurtTime = hurtTime
        this.onHurtFunc = hurtFunc
        this.endTime = endTime
        this.onEndFunc = endFunc
        this.nowTime = 0;
        this.isAttack = true;
        return true;
    }

    /**
     * 停止攻击
     */
    public stopAttack() {
        this.isAttack = false;
        this.hurtTime = 0;
        this.onHurtFunc = null;
        this.endTime = 0;
        this.onEndFunc = null;
    }

    protected update(dt: number): void {
        if (!this.isAttack) {
            return;
        }
        this.nowTime += dt;
        if (this.nowTime >= this.hurtTime) {
            if (this.onHurtFunc) {
                this.onHurtFunc()
                this.onHurtFunc = null;
            }
        }
        if (this.nowTime >= this.endTime) {
            if (this.onEndFunc) {
                this.onEndFunc()
                this.onEndFunc = null;
            }
            this.isAttack = false;
        }
    }


}